package com.itheima.reggie.controller;

import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){

        //1. 生成验证码，发送短信
        String code =  "1234";//ValidateCodeUtils.generateValidateCode(4);
        //不需要真实去发送了，主要是为方便
        // SMSUtils.sendMessage("黑马旅游网","SMS_205126318",user.getPhone(),code+"");
        //2. 把验证码存储到session中
        //session.setAttribute(user.getPhone(),code); //13556082481

        //存储验证码到Redis里,有效期五分钟
        redisTemplate.opsForValue().set(user.getPhone(),code,5, TimeUnit.MINUTES);



        log.info("本次验证码："+ code);

        return R.success("发送成功");
    }

    /**
     * 登录功能
     * @param param
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> param, HttpSession session) {

        String phone = param.get("phone");
        String inputCode = param.get("code");
        String verifyCode = (String) redisTemplate.opsForValue().get(phone);

        User user = userService.login(inputCode,verifyCode,phone);

        if (user != null){
            redisTemplate.delete(phone);
            session.setAttribute("user",user.getId());
        }else {
            return R.error("登录失败");
        }
        return R.success(user);
    }

    /**
     * 退出功能
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }



}
